<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { UserService } from '@/service'
import { ID_TYPE } from '@/constants/Constants'
import type { LoginForm, RegisterForm, ResponseBody } from '@/types/SharedTypes'
import { useAuthStore } from '@/stores/authStore'
import { useRouter } from 'vue-router'


let currentAction = ref('login')
const authStore = useAuthStore()
const router = useRouter()

const loginFormInfo = reactive<LoginForm>({
  usernameOrMailOrPhone: '',
  password: ''
})
const registerFormInfo = reactive<RegisterForm>({
  username: '',
  password: '',
  realName: '',
  idType: null,
  idCard: '',
  telephone: '',
  mail: ''
})
const loginRuleRef = ref<FormInstance>()
const registerRuleRef = ref<FormInstance>()

const switchToLogin = () => {
  // 清除注册信息
  resetForm(registerRuleRef.value)
  // 重置页面展示标志
  currentAction.value = 'login'
}

const switchToRegister = () => {
  // 清除登录信息
  resetForm(loginRuleRef.value)
  // 重置页面展示标志
  currentAction.value = 'register'
}

const onSubmit = (formEl: FormInstance | undefined) => {
  if (currentAction.value === 'login') {
    // 处理登录逻辑
    handleLogin(formEl)
  } else if (currentAction.value === 'register') {
    // 处理注册逻辑
    handleRegister(formEl)
  }
}

const handleLogin = (formEl: FormInstance | undefined) => {

  if (!formEl) return
  formEl.validate( async (valid) => {
    if (valid) {
      const res: ResponseBody = await UserService.login(loginFormInfo)

      if (res.success) {
        authStore.login(res.data?.accessToken, res.data?.username)
        await router.push('/ticketSearch')
        ElMessage({
          message: '登录成功',
          type: 'success'
        })
      } else {
        ElMessage.error(res.message)
      }
    } else {
      ElMessage.error('提交错误!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const loginRules = reactive<FormRules<LoginForm>>({
  usernameOrMailOrPhone: [
    { required: true, message: '用户名为必填项！', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码为必填项！', trigger: 'blur' }
  ]
})

const handleRegister = (formEl: FormInstance | undefined) => {

  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      UserService.register(registerFormInfo)
        .then((res) => {
          if (res.success) {
            ElMessage({
              message: '注册成功',
              type: 'success'
            })

            // 记录注册用户名
            const username = registerFormInfo.username

            // 切换表单后自动用户名赋值
            resetForm(registerRuleRef.value)
            currentAction.value = 'login'
            loginFormInfo.usernameOrMailOrPhone = username
          } else {
            ElMessage.error(res.message)
          }
        })
    } else {
      ElMessage.error('提交错误!')
      return false
    }
  })
}

const checkIdType = (rule: any, value: any, callback: any) => {
  if (!registerFormInfo.idType) {
    return callback(new Error('请先选择证件类型'))
  }
}

const registerRules = reactive<FormRules<RegisterForm>>({
  username: [
    { required: true, message: '用户名为必填项！', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码为必填项！', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '真实姓名为必填项！', trigger: 'blur' }
  ],
  idType: [
    { required: true, message: '证件类型必填项！', trigger: 'blur' }
  ],
  idCard: [
    { validator: checkIdType, trigger: 'blur' },
    { required: true, message: '证件号码为必填项！', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '电话号码为必填项！', trigger: 'blur' }
  ],
  mail: [
    { required: true, message: '邮箱为必填项！', trigger: 'blur' }
  ]
})
</script>

<template>
  <div class="login-reg-panel">
    <div class="login-info-box" :class="{ active: currentAction === 'login' }">
      <h2>已有账号？</h2>
      <h3>欢迎登录账号！</h3>
      <button @click="switchToLogin" v-if="currentAction !== 'login'">去登录</button>
    </div>
    <div class="register-info-box" :class="{ active: currentAction === 'register' }">
      <h2>没有账号？</h2>
      <h3>欢迎注册账号！</h3>
      <button @click="switchToRegister" v-if="currentAction !== 'register'">去注册</button>
    </div>
    <div class="white-panel" :class="{ 'white-panel-left': currentAction === 'register' }">
      <div class="login-show" v-if="currentAction === 'login'">
        <el-form
          ref="loginRuleRef"
          :rules="loginRules"
          label-position="right"
          label-width="auto"
          :model="loginFormInfo"
          style="max-width: 400px"
        >
          <el-form-item label="用户名" prop="usernameOrMailOrPhone">
            <el-input v-model="loginFormInfo.usernameOrMailOrPhone" placeholder="请输入用户名、邮箱或手机号码" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginFormInfo.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit(loginRuleRef)">登录</el-button>
            <el-button @click="resetForm(loginRuleRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="register-show" v-else>
        <el-form
          ref="registerRuleRef"
          :rules="registerRules"
          label-position="right"
          label-width="auto"
          :model="registerFormInfo"
          style="max-width: 400px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerFormInfo.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerFormInfo.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="registerFormInfo.realName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="证件类型" prop="idType">
            <el-select v-model="registerFormInfo.idType" placeholder="请选择证件类型">
              <el-option v-for="type in ID_TYPE" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码" prop="idCard">
            <el-input v-model="registerFormInfo.idCard" placeholder="请输入证件号码" />
          </el-form-item>
          <el-form-item label="手机号码" prop="telephone">
            <el-input v-model="registerFormInfo.telephone" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="邮件" prop="mail">
            <el-input v-model="registerFormInfo.mail" placeholder="请输入邮箱账号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit(registerRuleRef)">注册</el-button>
            <el-button @click="resetForm(registerRuleRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/variables.scss';

.login-wrapper {
  width: 100%;
  height: 100%;
  background-clip: padding-box;
  background: url('https://nacos.io/img/black_dot.png');
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.9);
  overflow: hidden;

  .login-reg-panel {
    position: relative;
    text-align: center;
    margin: auto;
    min-width: 800px;
    height: 600px;
    background-color: $theme-color;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.9);

    .login-info-box,
    .register-info-box {
      display: inline-block;
      cursor: pointer;
      padding: 10px;
      transition: background-color 0.3s ease;
    }

    .active {
      background-color: $theme-color;
    }
  }

  .white-panel {
    transition: 0.3s ease-in-out;
    margin: 0 20%;

    &.white-panel-left {
      transform: translateX(+50%);
    }
  }
}
</style>